#!/usr/local/env python
# -*- coding: utf-8 -*-
import os
import logging


def logging_init(config=None):
    """
    Initialize logging faculty
    """
    level = config.getint("agent", "logging_level")

    if os.name == "nt":
        log_file = os.path.expandvars(config.get("agent", "log_file"))
    else:
        log_file = config.get("agent", "log_file")

    log_file_mode = config.get("agent", "log_file_mode")
    if log_file_mode in ("w", "a"):
        pass
    elif log_file_mode == "truncate":
        log_file_mode = "w"
    elif log_file_mode == "append":
        log_file_mode = "a"
    else:
        log_file_mode = "a"

    if log_file == "-":
        logging.basicConfig(level=level)  # Log to sys.stderr by default
    else:
        try:
            logging.basicConfig(
                filename=log_file,
                filemode=log_file_mode,
                level=level,
                format="%(asctime)-15s  %(levelname)s %(message)s",
            )
        except IOError as e:
            logging.basicConfig(level=level)
            logging.info("IOError: %s", e)
            logging.info("Drop logging to stderr")

    logging.info("Agent logging_level %i", level)
